package com.rzj.book.service.impl;

import com.rzj.book.dao.IMenuDao;
import com.rzj.book.dao.IRoleDao;
import com.rzj.book.en.Menu;
import com.rzj.book.en.Role;
import com.rzj.book.en.Tree;
import com.rzj.book.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName RoleServiceImpl
 * @Description TODO
 * @Author Administrator
 * @Date 2020/5/20 20:15
 * @Version 1.0
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IMenuDao menuDao;

    @Override
    public List<Tree> readRoleMenus(Integer id) {
        List<Tree> treeList = new ArrayList<Tree>();
        //获取角色信息
        Role role = roleDao.getRoleById(id);
        //获取角色菜单
        List<Menu> roles = new ArrayList<>();
        List<Long> rolesList = new ArrayList<>();
        if(role != null && !role.getMenus().isEmpty()){
            roles = role.getMenus();
            for(int i= 0;i<roles.size();i++)
            rolesList.add(roles.get(i).getMenuid());
        }

        Menu root = menuDao.getALLMenu(0);
        Tree t1 = null, t2 = null;
        for (Menu m : root.getMenus()) {
            t1 = new Tree();
            t1.setId(m.getMenuid());
            t1.setText(m.getMenuName());
            //二级菜单
            for (Menu m2 : m.getMenus()) {
                t2 = new Tree();
                t2.setId(m2.getMenuid());
                t2.setText(m2.getMenuName());
                //如果角色下包含权限菜单，让它勾选上
                if (rolesList.contains(m2.getMenuid())) {
                    t2.setChecked(true);
                }
                t1.getChildren().add(t2);
            }
            treeList.add(t1);
        }

        return treeList;
    }

    @Override
    public List<Role> getRoleList() {
        return roleDao.getRoleList();
    }

    @Override
    public List<Role> getRoleListByEmpId(Integer empId) {
        return roleDao.getRoleListByEmpId(empId);
    }
}
